import React, { useEffect, useState } from 'react';
import { Card, Tag, Space, Typography, Descriptions } from 'antd';
import type { DescriptionsProps } from 'antd';
import http from '~/api/http';
import type { IGanyux } from '~/types/ganyux';

// 状态配置（新增样式相关属性）
const STATUS_CONFIG = [
  { value: 0, label: '正常', color: 'success', bgColor: '#f6ffed', borderColor: '#52c41a', textColor: '#333' },
  { value: 1, label: '轻度', color: 'processing', bgColor: '#e6f7ff', borderColor: '#1890ff', textColor: '#333' },
  { value: 2, label: '中度', color: 'warning', bgColor: '#fffbe6', borderColor: '#faad14', textColor: '#333' },
  { value: 3, label: '偏重', color: 'error', bgColor: '#fff2e8', borderColor: '#ff7a45', textColor: '#333' },
  { value: 4, label: '严重', color: 'error', bgColor: '#fff1f0', borderColor: '#f5222d', textColor: '#333' },
];

// 症状字段中文映射
const SYMPTOM_LABELS = {
  xin: '躯体化',
  xin1: '强迫症化',
  xin2: '人际关系敏感',
  xin3: '犹豫',
  xin4: '焦虑',
  xin5: '敌对',
  xin6: '恐怖',
  xin7: '偏执',
  xin8: '精神病性',
  depression: '抑郁', 
};

// 时间格式化工具函数
const formatDate = (dateStr: string | number | undefined): string => {
  if (!dateStr) return '未知时间';
  const timestamp = typeof dateStr === 'number' ? dateStr : new Date(dateStr).getTime();
  if (isNaN(timestamp)) return '无效时间';
  
  const date = new Date(timestamp);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
};

interface AddFormProps1 {
  onSuccess?: () => void;
  onCancel?: () => void;
  value: number;
}

const App: React.FC<AddFormProps1> = ({ onSuccess, onCancel, value }) => {
  const [memberInfo, setMemberInfo] = useState<DescriptionsProps['items']>([]);
  const [symptomGroups, setSymptomGroups] = useState<Record<number, string[]>>({ 0: [], 1: [], 2: [], 3: [], 4: [] });
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  const fetchData = async () => {
    try {
      setLoading(true);
      const response = await http.getList<IGanyux>('Ganyux/chay', {});
      const memberData = response.data.filter(item => item.id === value)[0];

      if (!memberData) {
        setError('未查询到会员数据');
        return;
      }

      // 处理会员基础信息（转换为Descriptions所需的items格式）
      const tempMemberInfo: DescriptionsProps['items'] = [
        {
          key: 'fileNumber',
          label: '档案编号',
          children: memberData.fileNumber || '无编号',
        },
        {
          key: 'name',
          label: '姓名',
          children: memberData.name || '未知',
        },
        {
          key: 'age',
          label: '年龄',
          children: memberData.age ? `${memberData.age}岁` : '未知',
        },
        {
          key: 'sex',
          label: '性别',
          children: memberData.sex || '未知',
        },
        {
          key: 'xdata',
          label: '注册时间',
          children: formatDate(memberData.xdata),
        },
      ];
      setMemberInfo(tempMemberInfo);

      // 处理症状分组
      const tempSymptomGroups: Record<number, string[]> = { 0: [], 1: [], 2: [], 3: [], 4: [] };
      const symptomKeys = Object.keys(SYMPTOM_LABELS);
      symptomKeys.forEach(key => {
        if (memberData.hasOwnProperty(key)) {
          const statusValue = Number(memberData[key]);
          if (STATUS_CONFIG.some(c => c.value === statusValue)) {
            tempSymptomGroups[statusValue].push(SYMPTOM_LABELS[key as keyof typeof SYMPTOM_LABELS]);
          }
        }
      });
      setSymptomGroups(tempSymptomGroups);
      setError('');
    } catch (err) {
      console.error('数据请求失败：', err);
      setError('会员数据加载失败，请重试');
      setMemberInfo([]);
      setSymptomGroups({ 0: [], 1: [], 2: [], 3: [], 4: [] });
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, [value]);

  if (loading) {
    return (
      <div style={{ padding: 20, textAlign: 'center', color: '#666' }}>
        <Typography.Text loading>加载会员数据中...</Typography.Text>
      </div>
    );
  }
  if (error) {
    return (
      <div style={{ padding: 20, textAlign: 'center', color: '#f5222d', fontSize: 14 }}>
        {error}
      </div>
    );
  }

  return (
    <div style={{ 
      padding: '16px', 
      maxWidth: 1000, 
      margin: '0 auto', 
      backgroundColor: '#fff', 
      borderRadius: 8 
    }}>
      <Typography.Title level={4} style={{ 
        margin: '0 0 16px 0', 
        paddingBottom: '8px', 
        borderBottom: '1px solid #f0f0f0',
        color: '#1890ff'
      }}>
        心理测详情
      </Typography.Title>

      {/* 会员档案（使用Descriptions组件） */}
      <Card 
        bordered={false} 
        style={{ 
          boxShadow: '0 1px 3px rgba(0,0,0,0.05)', 
          borderRadius: 6,
          borderLeft: '3px solid #1890ff',
          marginBottom: '16px'
        }}
        bodyStyle={{ padding: '16px' }}
      >
        <Descriptions 
          title="会员档案" 
          items={memberInfo} 
          column={{ xs: 1, sm: 2, md: 3, lg: 3, xl: 3, xxl: 3 }}
        />
      </Card>

      {/* 症状状态分类 */}
      <Typography.Text strong style={{ fontSize: 14, color: '#333', display: 'block', marginBottom: '8px' }}>
        症状状态分类（相同程度聚合）
      </Typography.Text>

      <Space direction="vertical" size="8px" style={{ width: '100%' }}>
        {STATUS_CONFIG.map(config => (
          <Card
            key={config.value}
            title={
              <Tag 
                color={config.color} 
                size="small"
                style={{ borderRadius: 4, fontSize: 14, fontWeight: 'bold', marginRight: '8px' }}
              >
                {config.label}
              </Tag>
            }
            bordered={false}
            style={{ 
              boxShadow: '0 1px 2px rgba(0,0,0,0.04)', 
              borderRadius: 6,
              borderLeft: `3px solid ${config.borderColor}`,
              background: config.bgColor,
              color: config.textColor
            }}
            bodyStyle={{ 
              padding: '12px 16px', 
              marginTop: 0 
            }}
            titleStyle={{ 
              padding: '8px 16px', 
              fontSize: 13, 
              fontWeight: 500,
              paddingBottom: 0,
              background: 'transparent'
            }}
          >
            {symptomGroups[config.value].length > 0 ? (
              <Space wrap size="middle">
                {symptomGroups[config.value].map(symptom => (
                  <Tag key={symptom} size="small" style={{ borderRadius: 4 }}>
                    {symptom}
                  </Tag>
                ))}
              </Space>
            ) : (
              <Typography.Text type="secondary" style={{ fontSize: 12, padding: '8px 0' }}>
                无该程度的症状
              </Typography.Text>
            )}
          </Card>
        ))}
      </Space>
    </div>
  );
};

export default App;